﻿using CQRS.Events;
using CQRS.Reports;
using CQRS.Sample.Domain.Events;
using CQRS.Sample.Domain.ReportDtos;

namespace CQRS.Sample.Domain.EventHandlers
{
    public class PlaneRepairedEventHandler : IEventHandler<PlaneRepairedEvent>
    {
        private readonly IReportingRepository _reportingRepository;

        public PlaneRepairedEventHandler(IReportingRepository reportingRepository)
        {
            _reportingRepository = reportingRepository;
        }

        #region IEventHandler<PlaneRepairedEvent> Members

        public void Execute(PlaneRepairedEvent theEvent)
        {
            _reportingRepository.Update<PlaneReport>
                (new QueryCriteria().AddCriteria("HasBeenRepaired", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));
            _reportingRepository.Update<PlaneDetailsReport>
                (new QueryCriteria().AddCriteria("HadBeenRepaired", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));
            _reportingRepository.Update<PlaneHistoryReport>
                (new QueryCriteria().AddCriteria("HadBeenRepaired", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));

            var planeRepairReport = new PlaneRepairReport(theEvent.PlaneId,
                                                          theEvent.EffectuatedBy, theEvent.RepairDate,
                                                          theEvent.RepairedPart,
                                                          theEvent.ChangedPart);
            _reportingRepository.Save(planeRepairReport);
        }

        #endregion
    }
}